package com.meixiang.adapter.personalCenter;

import android.app.Activity;
import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.lzy.okhttputils.model.HttpParams;
import com.meixiang.R;
import com.meixiang.activity.account.myShopper.MyAllOrderActivity;
import com.meixiang.activity.account.myShopper.OrderDetailActivity;
import com.meixiang.activity.account.myShopper.OrderEvaluationActivity;
import com.meixiang.activity.account.myShopper.OrderForCheckLogisticsActivity;
import com.meixiang.activity.account.myShopper.OrderRefundActivity;
import com.meixiang.activity.homes.shopping.CashierDeskActivity;
import com.meixiang.entity.OrderResult;
import com.meixiang.entity.myOrder.MyOrderDetail;
import com.meixiang.entity.myOrder.OrderUtils;
import com.meixiang.global.Config;
import com.meixiang.global.GlobalType;
import com.meixiang.http.HttpCallBack;
import com.meixiang.http.HttpUtils;
import com.meixiang.tool.Tool;
import com.meixiang.util.AbStrUtil;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * @author yinsujun  Created at 2016/5/9 10:27
 */
public class AllOrderAdapter extends RecyclerView.Adapter<AllOrderAdapter.ViewHolder> {
    private MyAllOrderActivity context;
    private String status;

    private List<MyOrderDetail> data=new ArrayList<>();


    public AllOrderAdapter(MyAllOrderActivity context,String status) {
        this.context = context;
        this.status=status;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.activity_my_all_order_list_item, parent, false);
        ViewHolder viewHolder = new ViewHolder(view);
        return viewHolder;
    }
    public void addAll(List<MyOrderDetail> orderDetails){
        this.data.addAll(orderDetails);
        this.notifyDataSetChanged();
    }
    public void clear(){
        this.data.clear();
        this.notifyDataSetChanged();
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, final int position) {

        final MyOrderDetail orderDetail = data.get(position);
        String orderStatus="";
        if(!AbStrUtil.isEmpty(status)){
            orderStatus=status;
        }else{
//            for(int i=0;i<orderDetail.getOrderGoodsList().size();i++){
//                orderStatus = OrderUtils.getOrderStatus(orderDetail.getOrderState(),orderDetail.getEvaluationStatus(),
//                        orderDetail.getOrderGoodsList().get(i).getRefundState());
//            }
            orderStatus = OrderUtils.getOrderStatus(orderDetail.getOrderState(),orderDetail.getEvaluationStatus());
        }
        if(orderStatus.equals("待收货")||orderStatus.equals("待发货")){
            holder.tvCheckLogistics.setVisibility(View.VISIBLE);
            holder.tvCheckLogistics.setText("查看物流");
            holder.tvStatus.setText("待收货");
            holder.tvCheckReceipt.setText("确认收货");
            holder.tvStatus.setTextColor(ContextCompat.getColor(context, R.color.order_status_color));
        }else if(orderStatus.contains("评价")){
            holder.tvCheckLogistics.setVisibility(View.VISIBLE);
            holder.tvCheckLogistics.setText("给它评价");
            holder.tvStatus.setText("待评价");
            holder.tvCheckReceipt.setText("删除订单");
            holder.tvStatus.setTextColor(ContextCompat.getColor(context, R.color.order_green_color));
        }else if(orderStatus.equals("待付款")){
            holder.tvCheckLogistics.setVisibility(View.VISIBLE);
            holder.tvCheckLogistics.setText("取消订单");
            holder.tvCheckReceipt.setText("去支付");
            holder.tvStatus.setText("待付款");
            holder.tvStatus.setTextColor(ContextCompat.getColor(context, R.color.order_red_color));
        }else if(orderStatus.equals("退款/售后")){

            holder.tvCheckLogistics.setVisibility(View.GONE);
            holder.tvStatus.setText("退款成功");
            holder.tvCheckReceipt.setText("钱款去向");
            holder.tvStatus.setTextColor(ContextCompat.getColor(context, R.color.order_red_color));
        }else if(orderStatus.equals("交易完成")){
            //待收货列表可查看
//            holder.tvCheckLogistics.setVisibility(View.GONE);
//            holder.tvStatus.setText("交易完成");
//            holder.tvCheckReceipt.setText("删除订单");
            holder.tvCheckLogistics.setVisibility(View.VISIBLE);
            holder.tvCheckLogistics.setText("给它评价");
            holder.tvStatus.setText("待评价");
            holder.tvCheckReceipt.setText("删除订单");
            holder.tvStatus.setTextColor(ContextCompat.getColor(context, R.color.black_3));
        }else if(orderStatus.equals("已取消")){
            holder.tvCheckLogistics.setVisibility(View.GONE);
            holder.tvStatus.setText("交易完成");
            holder.tvCheckReceipt.setText("删除订单");
            holder.tvStatus.setTextColor(ContextCompat.getColor(context, R.color.black_3));
        }else{
            holder.tvStatus.setTextColor(ContextCompat.getColor(context, R.color.black_3));
        }

        if(orderStatus.equals("退款/售后")){
            holder.tvStatus.setText(OrderUtils.getRefund(orderDetail.getOrderState()));

        }else {
//            for (int i = 0; i < orderDetail.getOrderGoodsList().size(); i++) {
//                holder.tvStatus.setText(OrderUtils.getOrderStatus(orderDetail.getOrderState(), orderDetail.getEvaluationStatus(),
//                        orderDetail.getOrderGoodsList().get(i).getRefundState()));
//            }
            holder.tvStatus.setText( OrderUtils.getOrderStatus(orderDetail.getOrderState(),orderDetail.getEvaluationStatus()));
        }




//        }

//        //支付状态——待付款0/已付款 1
//        if(("0").equals(orderDetail.getPaymentState())){
//            holder.tvCheckLogistics.setVisibility(View.VISIBLE);
//            holder.tvCheckLogistics.setText("取消订单");
//            holder.tvCheckReceipt.setText("去支付");
//            holder.tvStatus.setText("待付款");
//        }else if(("1").equals(orderDetail.getPaymentState())){
//            //已付款
//        }

        if(!AbStrUtil.isEmpty(orderDetail.getStoreName())){
            holder.tvName.setText(orderDetail.getStoreName());
        }
        String getOrderStatus="";
//        for(int i=0;i<orderDetail.getOrderGoodsList().size();i++){
//            if(AbStrUtil.isEmpty(orderDetail.getOrderGoodsList().get(i).getRefundState())){
//                getOrderStatus=OrderUtils.getOrderStatus(orderDetail.getOrderState(),orderDetail.getEvaluationStatus(),
//                        orderDetail.getOrderGoodsList().get(i).getRefundState());
//                break;
//            }else{
//                getOrderStatus=OrderUtils.getOrderStatus(orderDetail.getOrderState(),orderDetail.getEvaluationStatus(),
//                        orderDetail.getOrderGoodsList().get(i).getRefundState());
//            }
//        }

        getOrderStatus=OrderUtils.getOrderStatus(orderDetail.getOrderState(),orderDetail.getEvaluationStatus());
        holder.tvMoney.setText("￥"+orderDetail.getOrderTotalPrice());
        if(orderStatus.equals("退款/售后")){
            holder.tvMoney.setText("￥"+orderDetail.getOrderGoodsList().get(0).getGoodsPrice());
        }
        if(getOrderStatus.equals("待付款")){
            holder.tvDisbursements.setText("应付款：");
        }else
        if(orderStatus.equals("退款/售后")){
            holder.tvDisbursements.setText("退款金额：");
        }else{
            holder.tvDisbursements.setText("实付款：");
        }
        holder.tvCheckLogistics.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent();
                if(holder.tvCheckLogistics.getText().toString().equals("待收货")){


                }else if(holder.tvCheckLogistics.getText().toString().equals("取消订单")){
                    // "待付款
                    cancelOrder(orderDetail.getOrderId());
                    return;
                }else if(holder.tvCheckLogistics.getText().toString().equals("给它评价")){
                    intent.setClass(context,OrderEvaluationActivity.class);
                    intent.putExtra("orderId",orderDetail.getOrderId());

                }else if(holder.tvCheckLogistics.getText().toString().equals("查看物流")){
                    //查看物流
                    intent.setClass(context,OrderForCheckLogisticsActivity.class);
                    intent.putExtra("orderId",orderDetail.getOrderId());
                    intent.putExtra("orderNo",orderDetail.getOrderSn());
                }else{
                    return;
                }
                context.startActivity(intent);
            }
        });
        holder.tvCheckReceipt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent();
                if(holder.tvCheckReceipt.getText().toString().equals("钱款去向")){
                    intent.setClass(context,OrderRefundActivity.class);
                    intent.putExtra("refundId",orderDetail.getRefundId());
                }else if(("删除订单").equals(holder.tvCheckReceipt.getText().toString())){
                    deleteOrder(orderDetail.getOrderId());
                    return;
                }else if(("去支付").equals(holder.tvCheckReceipt.getText().toString())){
                    OrderResult mOrderResult=new OrderResult(orderDetail.getOrderTotalPrice(),orderDetail.getOrderId());
                    Log.e("TAG","测试传人数据mOrderResult"+mOrderResult.toString());
                    Log.e("TAG","测试传人数据mOrderResult"+mOrderResult.getOrderId());
                    intent.setClass(context,CashierDeskActivity.class);
                    intent.putExtra(CashierDeskActivity.ORDER_TYPE,"SC");
                    intent.putExtra(CashierDeskActivity.ORDER_RESULT,mOrderResult);
                    intent.putExtra(CashierDeskActivity.PAYMENT_TYPE, CashierDeskActivity.ORDER_PAY);
                    intent.putExtra(GlobalType.ORDER_PAYMENT_TYPE, CashierDeskActivity.MY_ORDER_SHOPPING_ORDER);
                    HashMap<String, Class> map = new HashMap<>();
                    map.put(CashierDeskActivity.GOTO_ACTIVITY, MyAllOrderActivity.class);
                    intent.putExtra(CashierDeskActivity.GOTO_ACTIVITY, map); // 支付成功之后跳转的activity
                }else if(("确认收货").equals(holder.tvCheckReceipt.getText().toString())){
                    confirmOrder(orderDetail.getOrderId());
                    return;
                }
                else{
                    return;
                }
                context.startActivity(intent);
            }
        });


        LinearLayoutManager linearLayoutManager=new LinearLayoutManager(context);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        holder.recyclerView.setLayoutManager(linearLayoutManager);
        AllOrderItemAdapter allOrderItemAdapter;
        if(data.size()>0){
            allOrderItemAdapter = new AllOrderItemAdapter(context, data.get(position));
        }else{
            allOrderItemAdapter = new AllOrderItemAdapter(context);
        }

        holder.recyclerView.setAdapter(allOrderItemAdapter);

        //数据条目点击
        final String finalOrderStatus = orderStatus;
        allOrderItemAdapter.setOnItemClickListener(new AllOrderItemAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int positions) {
                Intent intent=new Intent(context,OrderDetailActivity.class);
                if(data.size()>0){
                    intent.putExtra("orderId",data.get(position).getOrderId());
                    intent.putExtra("refundId",orderDetail.getRefundId());
                }
                intent.putExtra("status", finalOrderStatus);
//                if(finalOrderStatus.equals("退款/售后")){
//                    intent.putExtra("refundId",orderDetail.getRefundId());
////                    intent.putExtra("orderGoodsId",orderDetail.getOrderGoodsList().get(0).getGoodsId());
////                    intent.putExtra("goodsId",orderDetail.getOrderGoodsList().get(0).getGoodsId());
//                }
                context.startActivity(intent);
            }
        });


    }

    @Override
    public int getItemCount() {
        return data.size();
    }
    class ViewHolder extends RecyclerView.ViewHolder{
        @Bind(R.id.order_item_tv_name)
        TextView tvName;
        @Bind(R.id.order_item_tv_status)
        TextView tvStatus;
        @Bind(R.id.order_item_recycler_view)
        RecyclerView recyclerView;
        /**
         * 实付款标识
         */
        @Bind(R.id.order_item_tv_disbursements)
        TextView tvDisbursements;
        @Bind(R.id.order_item_tv_money)
        TextView tvMoney;
        @Bind(R.id.order_item_tv_check_logistics)
        TextView tvCheckLogistics;
        @Bind(R.id.order_item_tv_check_receipt)
        TextView tvCheckReceipt;
        ViewHolder(View view) {
            super(view);
            ButterKnife.bind(this, view);
        }
    }
    /**
    *取消订单
    *@author yinsujun
    *created at 2016/5/25 17:13
    */
    private void cancelOrder(final String orderId){
        String url= Config.ORDER_FOR_CANCEL_ORDER;
        HttpParams params=new HttpParams();
        params.put("orderId",orderId);
        HttpUtils.post(url, params, new HttpCallBack((Activity)context,"取消中...") {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
//                context.getData();
                notifyOrderList(orderId);
                Tool.showTextToast(context,message);
            }

            @Override
            public void onError(String code, String message) {
                Tool.showTextToast(context,message);
            }
        });

    }
    /**
    *删除订单
    *@author yinsujun
    *created at 2016/5/25 17:13
    */
    private void deleteOrder(final String orderId){
        String url=Config.ORDER_FOR_DELETE_ORDER;
        HttpParams params=new HttpParams();
        params.put("orderId",orderId);
        HttpUtils.post(url, params, new HttpCallBack((Activity)context,"删除中...") {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                notifyOrderList(orderId);
                Tool.showTextToast(context,message);
            }

            @Override
            public void onError(String code, String message) {
                Tool.showTextToast(context,message);
            }
        });
    }
    /**
     *确认订单
     *@author yinsujun
     */
    private void confirmOrder(final String orderId){
        String url=Config.ORDER_FOR_COMMIT_CONFIRM;
        HttpParams params=new HttpParams();
        params.put("orderId",orderId);
        HttpUtils.post(url, params, new HttpCallBack((Activity)context,"确认中...") {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                notifyOrderList(orderId);
                Tool.showTextToast(context,message);
            }

            @Override
            public void onError(String code, String message) {
                Tool.showTextToast(context,message);
            }
        });
    }

    /**
     * 取消删除订单成功，刷新页面
     * @param orderId
     */
    public void notifyOrderList(String orderId){
        for(int i=0;i<data.size();i++){
            if(data.get(i).getOrderId().equals(orderId)){
//                if(!AbStrUtil.isEmpty(status)){
                    data.remove(data.get(i));
                    this.notifyItemRemoved(i);
//                }else{
                    context.onRefresh();
//                }

            }

        }
    }



}
